


import React, { useEffect, useState } from 'react';
import { Card, Button } from 'antd';
import { Link, useNavigate } from 'react-router-dom';

import { fetchGoodsData } from '../../../../apis/goods';

const { Meta } = Card;

const GoodsList = () => {
  const [goodsData, setGoodsData] = useState([]);
  const [sortType, setSortType] = useState('default');
  const navigate = useNavigate();

  useEffect(() => {
    const fetchData = async () => {
      const data = await fetchGoodsData();
      setGoodsData(data);
    };

    fetchData();
  }, []);

  const handleCardClick = (id) => {
    navigate({ pathname: '/detail', search: `?id=${id}` });
  };

  const handlePriceSort = () => {
    if (sortType === 'priceAsc') {
      setSortType('priceDesc');
      setGoodsData([...goodsData].sort((a, b) => b.price - a.price));
    } else {
      setSortType('priceAsc');
      setGoodsData([...goodsData].sort((a, b) => a.price - b.price));
    }
  };

  const handleSalesSort = () => {
    if (sortType === 'salesAsc') {
      setSortType('salesDesc');
      setGoodsData([...goodsData].sort((a, b) => b.sales - a.sales));
    } else {
      setSortType('salesAsc');
      setGoodsData([...goodsData].sort((a, b) => a.sales - b.sales));
    }
  };

  return (
    <div>
      <div className="shengxian wrapper">
        <div className="hd">
          <h2>猜你喜欢！</h2>
          <Link to="#" className="more">查看全部</Link>
          <ul>
            <li><a href="#">个性推荐</a></li>
          </ul>
        </div>
        <div className="bd clearfix">
          <div className="sort-buttons">
            <Button onClick={handlePriceSort}>
              {sortType === 'priceAsc' ? '价格升序' : '价格降序'}
            </Button>
            <Button onClick={handleSalesSort}>
              {sortType === 'salesAsc' ? '销量升序' : '销量降序'}
            </Button>
          </div>
          {goodsData.map((goods) => (
            <Card
              key={goods.id}
              className="card"
              hoverable
              style={{
                width: 250,
              }}
              cover={<img alt={goods.name} src={require(`../../../../static/image/`+goods.images[0])} />}
              onClick={() => handleCardClick(goods.id)}
            >
              <Meta className='txt' title={goods.name} />
              <div className='txt_item'>
              <h3>￥{goods.price}</h3>
              <p>销量：{goods.sales}</p>
              </div>
            </Card>
          ))}
        </div>
      </div>
    </div>
  );
};

export default GoodsList;
